package com.hf.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hf.config.JwtConfig;

import io.jsonwebtoken.Claims;

/**
 * Token 拦截器
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
	@Resource
	private JwtConfig jwtConfig;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		// 允许跨域的主机地址
		response.setHeader("Access-Control-Allow-Origin", "*");
		// 地址过滤
		String uri = request.getRequestURI();
		if (uri.contains("/login") || uri.contains("/error")) {
			return true; // 放行
		}
		// Token 验证
		String token = request.getHeader("token");
		if (StringUtils.isEmpty(token)) {
			token = request.getParameter("token");
		}
		if (StringUtils.isEmpty(token)) {
			throw new Exception("token不能为空");
		}
		Claims claims = jwtConfig.getTokenClaim(token);
		if (claims == null || jwtConfig.isTokenExpired(claims.getExpiration())) {
			response.sendRedirect("http://127.0.0.1:8848/crmproject服务器上的/login.html");
			throw new Exception("token失效，请重新登录");
	
		}
		// 设置 identityId 用户身份ID
		request.setAttribute("identityId", claims.getSubject());
		return true; // 放行
	}
}